#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Author  : hu_cl
# @Contact : 760730895@qq.com
# @Date    : 2020/7/16 10:13
# @File    : post_syslog.py
import os
import subprocess
import cx_Oracle
import re

os.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.UTF8'


def data_to_oracle():
    with open("/var/log/11.1.117.19/syslog", encoding='iso-8859-1') as fp:
        for line in fp:
            line = line.encode('iso-8859-1').decode('gbk')
            data_processing(line)


def pg_data_to_oracle():
    p = subprocess.Popen('tailf /var/log/11.1.117.19/syslog', shell=True, stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE, encoding='iso-8859-1')  # 起一个进程，执行shell命令
    while True:
        line = p.stdout.readline()  # 实时获取行
        if line:  # 如果行存在的话
            line = line.encode('iso-8859-1').decode('gbk')
            data_processing(line)


def data_processing(line):
    print(line)
    data = {}
    content = ''.join(re.findall(r"Content=\"(.*?)\"", line))
    gentile = ''.join(re.findall(r"GenTime=\"(.*?)\"", line))
    b = line.split()

    for i in b[5:]:
        j = i.split("=", 1)
        if len(j) == 2:
            k, v = j[0].strip(), j[1].strip('"')
            data[k] = v

    item = {
        'SERIAL_NUM': data['SerialNum'] if 'SerialNum' in data else None,
        'GEN_TIME': gentile if 'GenTime' in data else None,
        'SRC_IP': data['SrcIP'] if 'SrcIP' in data else None,
        'SRC_IP6': data['SrcIP6'] if 'SrcIP6' in data else None,
        'SRC_IPVER': data['SrcIPVer'] if 'SrcIPVer' in data else None,
        'DST_IP': data['DstIP'] if 'DstIP' in data else None,
        'DST_IP6': data['DstIP6'] if 'DstIP6' in data else None,
        'DST_IPVER': data['DstIPVer'] if 'DstIPVer' in data else None,
        'PROTOCOL': data['Protocol'] if 'Protocol' in data else None,
        'SRC_PORT': data['SrcPort'] if 'SrcPort' in data else None,
        'DST_PORT': data['DstPort'] if 'DstPort' in data else None,
        'IN_INTERFACE': data['InInterface'] if 'InInterface' in data else None,
        'OUT_INTERFACE': data['OutInterface'] if 'OutInterface' in data else None,
        'SMAC': data['SMAC'] if 'SMAC' in data else None,
        'DMAC': data['DMAC'] if 'DMAC' in data else None,
        'FW_POLICY_ID': data['FwPolicyID'] if 'FwPolicyID' in data else None,
        'EVENT_NAME': data['EventName'] if 'EventName' in data else None,
        'EVENT_ID': data['EventID'] if 'EventID' in data else None,
        'EVENT_LEVEL': data['EventLevel'] if 'EventLevel' in data else None,
        'EVENTSET_NAME': data['EventsetName'] if 'EventsetName' in data else None,
        'SECURITY_TYPE': data['SecurityType'] if 'SecurityType' in data else None,
        'SECURITY_ID': data['SecurityID'] if 'SecurityID' in data else None,
        'PROTOCOL_ID': data['ProtocolID'] if 'ProtocolID' in data else None,
        'PROTOCOL_TYPE': data['ProtocolType'] if 'ProtocolType' in data else None,
        'ACTION': data['Action'] if 'Action' in data else None,
        'VSYSID': data['Vsysid'] if 'Vsysid' in data else None,
        'CONTENT': content if 'Content' in data else None,
        'CAP_TOKEN': data['CapToken'] if 'CapToken' in data else None,
        'EVT_COUNT': data['EvtCount'] if 'EvtCount' in data else None,
        'CPUUSAGE': data['CpuUsage'] if 'CpuUsage' in data else None,
        'MEMORYUSAGE': data['MemoryUsage'] if 'MemoryUsage' in data else None,
        'SESSIONNUM': data['SessionNum'] if 'SessionNum' in data else None,
        'HALFSESSIONNUM': data['HalfSessionNum'] if 'HalfSessionNum' in data else None,
        'BAND': data['Band'] if 'Band' in data else None,
        'ETH2BAND': data[' Eth2Band'] if ' Eth2Band' in data else None,
        'ETH3BAND': data['Eth3Band'] if 'Eth3Band' in data else None,
        'ETH4BAND': data['Eth4Band'] if 'Eth4Band' in data else None,
        'SYSBPS': data['Sysbps'] if 'Sysbps' in data else None,
    }
    print(item)
    # insert_data('INTRUSION_TESTING_LOG', item)


def insert_data(table, item):
    con = cx_Oracle.connect('ZNKSH', 'Admin123', '192.168.2.95:1521/ORCL')  # 创建连接
    cursor = con.cursor()  # 创建游标
    insert_data_list = []
    keys, vals = list(item.keys()), list(item.values())
    field = ','.join(keys)
    val = ','.join([':{}'.format(i) for i in range(1, len(item) + 1)])
    insert_sql = "insert into " + table + " (" + field + ") VALUES (" + val + ")"
    insert_data_list.append(vals)
    if len(insert_data_list) == 1:
        try:
            cursor.executemany(insert_sql, insert_data_list)
        except Exception as e:
            print(f'插入数据出错, {e}')
            raise e
        else:
            con.commit()
            insert_data_list.clear()
            cursor.close()  # 关闭游标
    con.close()  # 关闭数据库连接


if __name__ == '__main__':
    data_to_oracle()
    # pg_data_to_oracle()
